import { agcCloudDB, cloudDBZone } from '@/AGC/manager'
import { useUserStore } from '@/stores/user'
import type { ExercisePlanI } from '@/types/exercise'
import type { FoodPlanI } from '@/types/food'
import agconnect from '@hw-agconnect/api'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

/** 随机获取四位验证数 */
export const getCode = () => {
  return Math.random().toString(36).substring(3, 7)
}

/** 截取指定字符前面的字符串并转为数字 */
export const getStringToNumber = (str: string, char: string) => {
  const index = str.lastIndexOf(char)
  return Number(str.slice(0, index))
}

/** 登出 */
export const clearInfo = async () => {
  // 删除token和用户信息
  const userStore = useUserStore()
  userStore.removeToken()
  userStore.removeUserInfo()
  userStore.removeUserFilter()
  // 关闭 云数据库
  if (cloudDBZone && agcCloudDB) {
    agcCloudDB.closeCloudDBZone(cloudDBZone)
  }
  // 登出
  try {
    await agconnect.auth().signOut()
  } catch (error) {
    ElMessage.error('登出失败')
    Promise.reject(error)
  }
}

/** 获取推荐摄入和消耗 */
export const getTotalCalories = (list: FoodPlanI[] | ExercisePlanI[]) => {
  const totalCalories = list.reduce((acc, curr) => {
    acc += curr.calories
    return acc
  }, 0)
  return totalCalories
}

/**
 * 获取MM月DD日
 * @param date YYYY-MM-DD
 * @returns MM月DD日
 */
export const formatDate = (date: string) => {
  const arr = date.split('-')
  const month = Number(arr[1])
  const day = Number(arr[2])
  return `${month}月${day}日`
}

/**
 * 获取日期中的天数
 * @param date YYYY-MM-DD
 * @returns 天数
 */
export const getDay = (date: string) => {
  const arr = date.split('-')
  return Number(arr[2])
}

/**
 * 获取一周的日期
 * @param value YYYY-MM-DD
 * @returns 一周的日期
 */
export const getWeekByDate = (value: string) => {
  const date = new Date(value)
  let week = date.getDay()
  let dateNum = 0
  const dateList = []

  if (week == 0) {
    dateNum = date.getTime() - 6 * 24 * 60 * 60 * 1000
  } else {
    week -= 1
    dateNum = date.getTime() - week * 24 * 60 * 60 * 1000
  }

  for (let i = 0; i < 7; i++) {
    const tempDate = dateNum + i * 24 * 60 * 60 * 1000
    dateList.push(dayjs(tempDate).format('YYYY-MM-DD'))
  }

  return dateList
}

/**
 * 获取指定月份的天数
 * @param dateString YYYY-MM-DD
 * @returns 天数
 */
export const getDays = (dateString: string) => {
  const year = Number(dateString.split('-')[0])
  const month = Number(dateString.split('-')[1])
  return new Date(year, month, 0).getDate()
}
